import json
import re

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.shortcuts import render
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection

import constants
from apps.company.models import Company
from apps.index.models import JobCategory
from apps.index.utils import get_categories
from apps.position.models import Position, ReceiveResume, CollectPosition
from apps.resume.models import UserResume


class CreatePositionView(LoginRequiredMixin, View):
    """创建新职位"""

    def get(self, request):
        user = request.user

        channel_dict = get_categories()

        try:
            company = Company.objects.get(user_id=user.id)
        except:
            company = None

        context = {
            "user": user if user else None,
            "channels": channel_dict,
            "company": company,  # 用户公司
        }
        return render(request, 'create.html', context)

    def post(self, request):
        user = request.user
        if not user:
            return render(request, "common/404.html")

        positionType = request.POST.get("positionType")
        positionName = request.POST.get("positionName")
        department = request.POST.get("department")
        jobNature = request.POST.get("jobNature")
        salaryMin = request.POST.get("salaryMin")
        salaryMax = request.POST.get("salaryMax")
        workAddress = request.POST.get("workAddress")
        work_year = request.POST.get("workYear")
        education = request.POST.get("education")
        positionAdvantage = request.POST.get("positionAdvantage")
        positionDetail = request.POST.get("positionDetail")
        positionAddress = request.POST.get("positionAddress")
        email = request.POST.get("email")
        forwardEmail = request.POST.get("forwardEmail")

        params_list = [
            positionType, positionName, department, jobNature, salaryMin, salaryMax, workAddress,
            positionAdvantage, positionDetail, positionAddress, email, forwardEmail
        ]
        # 校验参数
        if not all(params_list):
            return http.JsonResponse({"errno": constants.INFO_MISSING, "errmsg": "请填写完整信息"})

        # 邮箱1
        if not re.match('^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'errno': constants.EMAILERROR, 'errmsg': '邮箱格式错误'})

        # 邮箱2
        if not re.match('^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', forwardEmail):
            return http.JsonResponse({'errno': constants.EMAILERROR, 'errmsg': '邮箱格式错误'})

        # 查询该用户的公司对象
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '系统繁忙1'})

        # 查询该公司是否发布了相同的职位
        try:
            positions = Position.objects.filter(company_id=company.id)
            for position in positions:
                # print('name-------', position.position_name)
                if position.position_name == positionName:
                    return http.JsonResponse({"errno": constants.POSITIONERR, 'errmsg': '该职位已经存在'})
        except:
            position = None

        if len(positionDetail) > 500:
            return http.JsonResponse({"errno": constants.DBERROR, "errmsg": "职位描述超过最大限度"})

        # 创建新职位
        try:
            position_obj = Position.objects.create(
                job_category=positionType,  # 职位类别
                position_name=positionName,  # 职位名称
                department=department,  # 所属部门
                job_nature=jobNature,  # 工作性质
                salary_min=salaryMin,  # 最低月薪
                salary_max=salaryMax,  # 最高月薪
                work_address=workAddress,  # 工作城市
                work_year=work_year,  # 工作经验
                education=education,  # 学历要求
                position_advantage=positionAdvantage,  # 工作经验
                position_detail=positionDetail,  # 学历要求
                position_address=positionAddress,  # 职位诱惑
                p_email=email,
                forward_email=forwardEmail,
                company_id=company.id,
                create_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S")
            )
        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '系统繁忙2'})

        # 储存到redis一个值返回成功页面
        redis_conn = get_redis_connection("status")
        # 建立管道
        status_id = "create_position_success%s" % user.id
        pl = redis_conn.pipeline()
        pl.set("create_position_success", status_id)
        pl.execute()

        return http.JsonResponse({"errno": constants.OK, 'errmsg': '创建成功'})


class CreatePositionSuccessView(LoginRequiredMixin, View):
    """创建新职位成功"""

    def get(self, request):
        user = request.user

        try:
            redis_conn = get_redis_connection("status")
            success_status = redis_conn.get("create_position_success")
            success_status = success_status.decode()
            # print(success_status)
            if success_status != "create_position_success%s" % user.id:
                return render(request, "common/404.html")

            redis_conn.delete("create_position_success")
        except:
            return render(request, "common/404.html")
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, 'common/404.html')
        context = {
            "user": user if user else None,
            "company": company,
        }
        return render(request, "createpositionsuccess.html", context=context)


class PositionListView(View):

    def get(self, request, category_id, page_num):
        user = request.user

        try:
            category = JobCategory.objects.get(id=category_id)
            # print(category)
        except:
            return http.HttpResponseNotFound("GoodsCategory does not found")

        # 匹配包含分类名称的职位
        pos = Position.objects.filter(position_name__contains=category.name, status=False, is_delete=False).order_by(
            "company_id")
        company = Company.objects.all().order_by("id")
        # 创建分页器
        paginator = Paginator(pos, constants.JOB_LIST_NUM)
        try:
            page_jobs = paginator.page(page_num)
        except:
            return http.HttpResponseNotFound('not found the page')
        total_page = paginator.num_pages

        # 查询用户公司
        try:
            user_com = Company.objects.get(user_id=user.id)
        except:
            user_com = None
        context = {
            "category": category,  # 分类
            'page_jobs': page_jobs,  # 分页后数据
            'page_num': page_num,  # 当前页数
            'total_page': total_page,  # 总页数
            'user_com': user_com,  # 用户公司
            'user': user,  # 用户
        }

        return render(request, "list.html", context)


class PositionDetailView(View):
    """职业详情页"""

    def get(self, request, position_id):
        """显示详情"""
        user = request.user

        # 查询当前详情页的职位对象
        try:
            position = Position.objects.get(id=position_id, status=False, is_delete=False)
        except:
            return http.HttpResponseBadRequest("sorry,没有该职位")

        try:
            resume = UserResume.objects.get(user_id=user.id)
        except:
            resume = None

        # 查询该用户是否投递过该职位
        try:
            rec_resume = ReceiveResume.objects.get(resume_id=resume, position_id=position.id)
        except:
            rec_resume = None

        # 查询用户公司
        try:
            user_com = Company.objects.get(user_id=user.id)
        except:
            user_com = None

        # 查询该用户是否收藏该工作
        try:
            collect_pos = CollectPosition.objects.get(user_id=user.id, position_id=position.id)
        except:
            collect_pos = None

        context = {
            "position": position,  # 该工作对象
            "user": user,  # 用户
            "user_com": user_com,  # 用户公司
            "resume": resume,  # 用户简历
            "rec_resume": rec_resume,  # 该用户是否投递简历
            "collect_pos": collect_pos,  # 该用户是否收藏该工作
        }
        return render(request, 'jobdetail.html', context=context)


class PositionValidView(LoginRequiredMixin, View):
    """有效职位"""

    def get(self, request):
        user = request.user

        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, 'common/404.html')
        try:
            position = Position.objects.filter(company_id=company.id, status=False, is_delete=False)
        except:
            position = None
        context = {
            "user": user if user else None,
            "company": company,  # 用户的公司
            "position": position,  # 公司发布的职位
        }
        print("有效职位")
        return render(request, 'positions.html', context)


class PositionDownlineView(LoginRequiredMixin, View):
    """职位下线与删除"""

    def get(self, request):

        user = request.user
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, 'common/404.html')
        try:
            position = Position.objects.filter(company_id=company.id, status=True, is_delete=False)
        except:
            position = None
        context = {
            "user": user if user else None,
            "company": company,  # 用户的公司
            "position": position,  # 公司发布的职位
        }
        return render(request, "posdownline.html", context)

    def post(self, request):
        user = request.user

        json_data = json.loads(request.body.decode())

        pos_id = json_data.get("pos_id")

        if not pos_id:
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': "没有该职位"})

        try:
            # company = Company.objects.get(user_id=user.id)
            position = Position.objects.get(id=pos_id)
            position.status = True
            position.save()
        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '下线失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': "下线成功"})

    def delete(self, request):
        user = request.user

        json_data = json.loads(request.body.decode())

        pos_id = json_data.get("pos_id")

        if not pos_id:
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': "没有该职位"})

        try:
            position = Position.objects.get(id=pos_id)
            position.is_delete = True
            position.save()
        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '删除失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': "删除成功"})


class InformInterviewView(LoginRequiredMixin, View):
    """通知面试"""

    def put(self, request):
        json_data = json.loads(request.body.decode())
        rec_resume_id = json_data.get("rec_resume_id")

        # 修改状态
        try:
            rece_resume = ReceiveResume.objects.get(id=rec_resume_id)
            rece_resume.status = 2
            rece_resume.save()
        except:
            return http.JsonResponse({"errno": constants.DBERROR, "errmsg": '通知失败'})
        return http.JsonResponse({'errno': constants.OK, 'errmsg': "通知成功"})

    def get(self, request):
        user = request.user
        # 查询该用户的公司
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, "common/404.html")
        # 查询该公司发布的职位
        try:
            position = Position.objects.filter(company_id=company.id)
            if position.count() == 0:
                position = None
        except:
            position = None
        pos_id_list = []
        if position != None:
            for pos in position:
                pos_id_list.append(pos.id)

        # 查询待定简历
        try:
            rec_resumes = ReceiveResume.objects.filter(position_id__in=pos_id_list, status=2)
        except:
            rec_resumes = None
        context = {
            "user": user,
            "company": company,  # 用户的公司
            "position": position,  # 公司发布的职位
            "rec_resumes": rec_resumes,  # 收到的简历
        }

        return render(request, "informinterview.html", context=context)


class UnableResumeView(LoginRequiredMixin, View):
    """不适合"""

    def get(self, request):
        user = request.user
        # 查询该用户的公司
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, "common/404.html")
        # 查询该公司发布的职位
        try:
            position = Position.objects.filter(company_id=company.id)
            if position.count() == 0:
                position = None
        except:
            position = None
        pos_id_list = []
        if position != None:
            for pos in position:
                pos_id_list.append(pos.id)

        print("存在01----------", pos_id_list)
        # 查询待定简历
        try:
            rec_resumes = ReceiveResume.objects.filter(position_id__in=pos_id_list, status=3)
        except:
            rec_resumes = None
        print("存在02----------", rec_resumes)
        context = {
            "user": user,
            "company": company,  # 用户的公司
            "position": position,  # 公司发布的职位
            "rec_resumes": rec_resumes,  # 收到的简历
        }

        return render(request, "haveRefuseResumes.html", context)

    def put(self, request):
        json_data = json.loads(request.body.decode())
        rec_resume_id = json_data.get("rec_resume_id")

        # 修改状态
        try:
            rece_resume = ReceiveResume.objects.get(id=rec_resume_id)
            rece_resume.status = 3
            rece_resume.save()
        except ReceiveResume.DoesNotExist as e:
            print(e)
            return http.JsonResponse({"errno": constants.DBERROR, "errmsg": '添加失败'})
        return http.JsonResponse({'errno': constants.OK, 'errmsg': "添加成功"})


class CollectPosView(LoginRequiredMixin, View):
    """收藏职位"""

    def post(self, request):
        user = request.user
        json_data = json.loads(request.body.decode())
        pos_id = json_data.get("pos_id")

        if not pos_id:
            return http.JsonResponse({'errno': constants.INFO_MISSING, "errmsg": "该职位不存在"})

        # 创建收藏职位的对象
        try:
            try:
                collect_pos = CollectPosition.objects.get(user_id=user.id, position_id=pos_id)
            except:
                collect_pos = None

            if collect_pos == None:
                collect_pos = CollectPosition.objects.create(
                    position_id=pos_id,
                    user_id=user.id,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                    create_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                return http.JsonResponse({"errno": constants.DBERROR, "errmsg": "该工作已被收藏"})
        except CollectPosition.DoesNotExist:
            return http.JsonResponse({"errno": constants.DBERROR, "errmsg": "收藏失败"})

        return http.JsonResponse({"errno": constants.OK, 'errmsg': "收藏成功"})

    def get(self, request):
        user = request.user
        # 查询该用户的公司
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            company = None

        try:
            collect_pos = CollectPosition.objects.filter(user_id=user.id)
        except:
            collect_pos = None

        context = {
            "user": user,  #
            "company": company,
            "collect_pos": collect_pos,
        }
        return render(request, "collections.html", context)

    def delete(self, request):
        user = request.user
        json_data = json.loads(request.body.decode())
        pos_id = json_data.get("pos_id")

        try:
            position = CollectPosition.objects.get(position_id=pos_id, user_id=user.id)
            position.delete()
        except:
            return http.JsonResponse({'errno': constants.DBERROR, "errmsg": '取消失败'})

        return http.JsonResponse({"errno": constants.OK, "errmsg": "取消成功"})
